package serie03;

import serie03.cmd.Command;
import serie03.cmd.InsertLine;
import serie03.cmd.DeleteLine;
import serie03.cmd.Clear;

public class StdEditor implements Editor {
	
	// ATTRIBUTS
	
	private Text text;
	private History<Command> history;
	
	// CONSTRUCTEURS
	
	public StdEditor() {
		this(DEFAULT_HISTORY_SIZE);
	}
	
	public StdEditor(int historySize) {
		if (historySize <= 0) {
			throw new IllegalArgumentException("Mauvaise taille");
		}
		history = new StdHistory<Command>(historySize);
		text = new StdText();
	}
	
	// REQUETES
	
	public int getTextLinesNb() {
		return text.getLinesNb();
	}
	
	public String getText() {
		return text.getContent();
	}
	
	public int getHistorySize() {
		return history.getMaxHeight();
	}
	
	public int nbOfPossibleUndo() {
		return history.getCurrentPosition() + 1;
	}
	
	public int nbOfPossibleRedo() {
		return history.getEndPosition() - history.getCurrentPosition();
	}
	
	// COMMANDES
	
	public void clear() {
		Clear cmd = new Clear(text);
		cmd.act();
		history.add(cmd);
	}
	
	public void insertLine(int numLine, String s) {
		if (1 > numLine || numLine > getTextLinesNb() + 1) {
			throw new IllegalArgumentException("Insertion impossible");
		}
		InsertLine cmd = new InsertLine(numLine, s, text);
		cmd.act();
		history.add(cmd);
	}
	
	public void deleteLine(int numLine) {
		if (1 > numLine || numLine > getTextLinesNb()) {
			throw new IllegalArgumentException("Suppression impossible");
		}
		String s = text.getLine(numLine);
		DeleteLine cmd = new DeleteLine(numLine, s, text);
		cmd.act();
		history.add(cmd);
	}
	
	public void undo() {
		if (nbOfPossibleUndo() <= 0) {
			throw new IllegalStateException("Impossible d'annuler");
		}
		history.getCurrentElement().act();
		history.goBackward();
	}
	
	public void redo() {
		if (nbOfPossibleRedo() <= 0) {
			throw new IllegalStateException("Impossible de refaire");
		}
		history.goForward();
		history.getCurrentElement().act();
	}

}
